// pages/profile/info/info.js
Page({
  data: {
    genders: ['男','女'],
    genderIndex: 0,
    form: {
      avatar: '/assets/images/default-avatar.jpg',
      name: '',
      signature: '',
      birthday: '',
      height: 170.0,
      weight: 52,
      initWeight: 52,
      initDate: '',
      targetWeight: 60,
      targetDate: '', // 用户选择的达成时间
      preference: '',
      allergy: '',
      special: ''
    },
    usingRxOptions: ['未使用','我正在使用'],
    usingRxIndex: 0,
    specialOptions: ['无','糖尿病','高血压','心脏病','其他'],
    specialIndex: 0,
    medicineOptions: ['请设置','二甲双胍','格列齐特','其他'],
    medicineIndex: 0,
    // 派生状态
    targetWeeks: '',
    targetDate: '',
    weightChangeType: '', // 增重/减重
    weeklyRate: '', // 每周变化率
    isDirty: false,
    // 底部弹窗
    showPicker: false,
    pickerType: '',
    pickerTitle: '',
    tempDate: '',
    tempValue: 170,
  },

  onLoad(){
    this.loadUserData();
  },

  onShow(){
    // 暂时注释掉自动重新加载，避免覆盖用户选择的数据
    // const user = wx.getStorageSync('user') || {};
    // if (user.height && user.height !== this.data.form.height) {
    //   this.loadUserData();
    // }
  },

  loadUserData(){
    const user = wx.getStorageSync('user') || {};
    const idx = this.data.genders.indexOf(user.gender||'保密');
    const specialIdx = this.data.specialOptions.indexOf(user.special||'无');
    const medicineIdx = this.data.medicineOptions.indexOf(user.medicine||'请设置');
    
    // 只更新form数据，不覆盖整个form对象
    this.setData({
      genderIndex: idx>=0?idx:0,
      specialIndex: specialIdx>=0?specialIdx:0,
      medicineIndex: medicineIdx>=0?medicineIdx:0,
      'form.avatar': user.avatar || this.data.form.avatar,
      'form.name': user.name || '',
      'form.signature': user.signature || '',
      'form.birthday': user.birthday || '',
      'form.height': (user.height && !isNaN(parseFloat(user.height))) ? parseFloat(user.height) : 170.0,
      'form.weight': (user.weight && !isNaN(parseFloat(user.weight))) ? parseFloat(user.weight) : 52,
      'form.initWeight': (user.initWeight && !isNaN(parseFloat(user.initWeight))) ? parseFloat(user.initWeight) : 52,
      'form.initDate': user.initDate || '',
      'form.targetWeight': (user.targetWeight && !isNaN(parseFloat(user.targetWeight))) ? parseFloat(user.targetWeight) : 60,
      'form.targetDate': user.targetDate || '',
      'form.preference': user.preference || '',
      'form.allergy': user.allergy || '',
      'form.special': user.special || '',
      'form.medicine': user.medicine || ''
    })
    this.computeTargets();
  },

  // 输入与选择
  onNameInput(e){ this.setData({ 'form.name': e.detail.value }) },
  onSignInput(e){ this.setData({ 'form.signature': e.detail.value }) },
  onHeightInput(e){ this.setData({ 'form.height': Number(e.detail.value) || 0 }, this.computeTargets) },
  onWeightInput(e){ this.setData({ 'form.weight': Number(e.detail.value) || 0 }, this.computeTargets) },
  onPrefInput(e){ this.setData({ 'form.preference': e.detail.value }) },
  onAllergyInput(e){ this.setData({ 'form.allergy': e.detail.value }) },
  onSpecialInput(e){ this.setData({ 'form.special': e.detail.value }) },
  onGenderChange(e){ this.setData({ genderIndex: Number(e.detail.value) }) },


  // 保存到本地缓存（可替换为后端接口）
  onSave(){
    const data = { ...this.data.form, gender: this.data.genders[this.data.genderIndex] }
    wx.setStorageSync('user', data)
    wx.showToast({ title: '已保存', icon: 'success' })
    setTimeout(()=>{ wx.navigateBack() }, 600)
  },

  onReset(){
    wx.removeStorageSync('user')
    this.setData({
      genderIndex: 0,
      form: {
        avatar: '/assets/images/default-avatar.jpg',
        name: '', signature: '', birthday:'', height: 170.0, weight: 52, initWeight: 52, initDate:'', targetWeight: 60, preference: '', allergy: '', special: ''
      }
    })
    wx.showToast({ title: '已恢复默认', icon: 'none' })
  },

  // 通过 wx.getUserProfile / wx.getUserInfo 获取头像昵称（新版本建议 chooseAvatar + type=nickname）
  getWxProfile(){
    if (wx.getUserProfile) {
      wx.getUserProfile({
        desc: '用于完善个人资料',
        success: res => {
          const nick = res.userInfo?.nickName || ''
          const avatar = res.userInfo?.avatarUrl || this.data.form.avatar
          this.setData({ 'form.name': nick, 'form.avatar': avatar })
          wx.showToast({ title: '已获取微信资料', icon:'none' })
        },
        fail: () => wx.showToast({ title:'用户取消授权', icon:'none' })
      })
    } else {
      wx.showToast({ title:'基础库较低，建议使用上方按钮选择头像', icon:'none' })
    }
  }
  ,

  // 打开底部选择器
  openPicker(e){
    const type = e.currentTarget.dataset.type;
    const titles = {
      gender: '性别',
      birthday: '生日',
      initDate: '初始日期',
      targetDate: '达成时间',
      height: '身高',
      currentWeight: '当前体重',
      initWeight: '初始体重',
      targetWeight: '目标体重',
      usingRx: '是否使用减重处方药',
      special: '特殊情况',
      medicine: '当前用药'
    }
    
    let tempValue = 170;
    if (type === 'height') {
      tempValue = this.data.form.height;
    } else if (type === 'currentWeight' || type === 'initWeight' || type === 'targetWeight') {
      tempValue = this.data.form[type === 'currentWeight' ? 'weight' : type];
    }
    
    // 设置tempDate的默认值
    let defaultDate = this._today();
    if (type === 'birthday') {
      defaultDate = this.data.form.birthday || this._today();
    } else if (type === 'initDate') {
      defaultDate = this.data.form.initDate || this._today();
    } else if (type === 'targetDate') {
      defaultDate = this.data.form.targetDate || this._today();
    }
    
    this.setData({
      showPicker: true,
      pickerType: type,
      pickerTitle: titles[type] || '选择',
      tempDate: defaultDate,
      tempValue: tempValue
    })
  },
  closePicker(){ this.setData({ showPicker:false }) },

  // 底部弹窗内交互
  selectGender(e){
    this.setData({ genderIndex: Number(e.currentTarget.dataset.index) })
  },
  onSheetDateChange(e){ this.setData({ tempDate: e.detail.value }) },
  onSheetHeightChange(e){ this.setData({ tempHeight: Number(e.detail.value) }) },
  
  onSheetWeightChange(e){ this.setData({ tempWeight: Number(e.detail.value) }) },
  selectUsingRx(e){ this.setData({ usingRxIndex: Number(e.currentTarget.dataset.index) }) },
  selectSpecial(e){ this.setData({ specialIndex: Number(e.currentTarget.dataset.index) }) },
  selectMedicine(e){ this.setData({ medicineIndex: Number(e.currentTarget.dataset.index) }) },
  
  // 数值输入处理
  onNumberInput(e) {
    const value = e.detail.value;
    this.setData({ tempValue: value });
  },
  
  onNumberBlur(e) {
    const value = parseFloat(e.detail.value);
    const type = this.data.pickerType;
    
    // 验证输入范围
    let min, max;
    if (type === 'height') {
      min = 100;
      max = 230;
    } else {
      min = 25;
      max = 200;
    }
    
    if (isNaN(value) || value < min || value > max) {
      wx.showToast({
        title: `请输入${min}-${max}之间的数值`,
        icon: 'none'
      });
      // 恢复原值
      if (type === 'height') {
        this.setData({ tempValue: this.data.form.height });
      } else if (type === 'currentWeight') {
        this.setData({ tempValue: this.data.form.weight });
      } else if (type === 'initWeight') {
        this.setData({ tempValue: this.data.form.initWeight });
      } else if (type === 'targetWeight') {
        this.setData({ tempValue: this.data.form.targetWeight });
      }
      return;
    }
    
    // 保留一位小数
    const roundedValue = Math.round(value * 10) / 10;
    this.setData({ tempValue: roundedValue });
    
    // 立即保存到form数据中
    // 直接更新form对象
    const newForm = { ...this.data.form };
    if (type === 'height') {
      newForm.height = roundedValue;
    } else if (type === 'currentWeight') {
      newForm.weight = roundedValue;
    } else if (type === 'initWeight') {
      newForm.initWeight = roundedValue;
    } else if (type === 'targetWeight') {
      newForm.targetWeight = roundedValue;
    }
    
    // 一次性更新整个form对象
    this.setData({ form: newForm });
    
    // 重新计算目标（因为体重数据可能影响计算）
    this.computeTargets();
    
    // 自动保存到本地存储
    this.autoSave();
    
    // 关闭弹窗
    this.setData({ showPicker: false });
  },
  savePicker(){
    const t = this.data.pickerType;
    
    if (t==='gender') { /* 已设置 genderIndex */ }
    else if (t==='birthday') { 
      this.setData({ 'form.birthday': this.data.tempDate });
    }
    else if (t==='initDate') { 
      this.setData({ 'form.initDate': this.data.tempDate });
    }
    else if (t==='targetDate') { 
      this.setData({ 'form.targetDate': this.data.tempDate });
    }
    else if (t==='height') { 
      const heightValue = parseFloat(this.data.tempValue);
      this.setData({ 'form.height': heightValue });
    }
    else if (t==='currentWeight') { 
      const weightValue = parseFloat(this.data.tempValue);
      this.setData({ 'form.weight': weightValue });
    }
    else if (t==='initWeight') { 
      const initWeightValue = parseFloat(this.data.tempValue);
      this.setData({ 'form.initWeight': initWeightValue });
    }
    else if (t==='targetWeight') { 
      const targetWeightValue = parseFloat(this.data.tempValue);
      this.setData({ 'form.targetWeight': targetWeightValue });
    }
    else if (t==='special') { 
      this.setData({ 'form.special': this.data.specialOptions[this.data.specialIndex] });
    }
    else if (t==='medicine') { 
      this.setData({ 'form.medicine': this.data.medicineOptions[this.data.medicineIndex] });
    }
    
    this.setData({ showPicker: false });
    this.computeTargets();
    this.autoSave();
  },

  // 计算目标周数与达成日期
  computeTargets(){
    const { weight, targetWeight, initWeight, initDate, targetDate } = this.data.form;
    
    // 判断是增重还是减重
    const isWeightGain = (targetWeight || 0) > (initWeight || 0);
    const weightChangeType = isWeightGain ? '增重' : '减重';
    
    // 计算体重差值
    const delta = Math.abs((targetWeight || 0) - (initWeight || 0));
    
    // 根据增重/减重设置每周标准
    const weeklyStandard = isWeightGain ? 0.09 : 0.10; // 增重0.09kg/周，减重0.10kg/周
    
    let weeks, dateStr, weeklyRate;
    
    if (targetDate && targetDate !== '') {
      // 用户选择了达成时间，需要重新计算每周标准
      const startDate = initDate ? new Date(initDate) : new Date();
      const endDate = new Date(targetDate);
      const timeDiff = endDate.getTime() - startDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      weeks = Math.ceil(daysDiff / 7);
      
      if (weeks > 0) {
        weeklyRate = delta / weeks; // 重新计算的每周变化率
        dateStr = targetDate;
      } else {
        weeks = Math.ceil(delta / weeklyStandard);
        weeklyRate = weeklyStandard;
        if (initDate) {
          const d = new Date(initDate);
          d.setDate(d.getDate() + weeks * 7);
          dateStr = `${d.getFullYear()}-${this._pad(d.getMonth()+1)}-${this._pad(d.getDate())}`;
        }
      }
    } else {
      // 使用默认每周标准计算
      weeks = Math.ceil(delta / weeklyStandard);
      weeklyRate = weeklyStandard;
      if (initDate) {
        const d = new Date(initDate);
        d.setDate(d.getDate() + weeks * 7);
        dateStr = `${d.getFullYear()}-${this._pad(d.getMonth()+1)}-${this._pad(d.getDate())}`;
      }
    }
    
    this.setData({ 
      targetWeeks: weeks ? `${weeks}` : '—', 
      targetDate: dateStr, 
      weightChangeType: weightChangeType,
      weeklyRate: weeklyRate ? weeklyRate.toFixed(3) : weeklyStandard.toFixed(3),
      isDirty: true 
    });
  },
  _today(){ const d=new Date(); return `${d.getFullYear()}-${this._pad(d.getMonth()+1)}-${this._pad(d.getDate())}` },
  _pad(n){ return String(n).padStart(2,'0') },

  // 自动保存到本地存储
  autoSave(){
    const data = { 
      ...this.data.form, 
      gender: this.data.genders[this.data.genderIndex],
      special: this.data.specialOptions[this.data.specialIndex],
      medicine: this.data.medicineOptions[this.data.medicineIndex]
    }
    
    wx.setStorageSync('user', data)
  },

})